// index.js
// 引入菜谱数据
const recipesData = require('../../data/new_recipes.js').default;

// 按年龄段整理菜谱数据
function organizeRecipesByAge(recipes) {
  const organized = {
    '6-8': [],
    '8-12': [],
    '12+': []
  };

  recipes.forEach(recipe => {
    const ageRange = recipe.ageRange;
    if (ageRange.includes('6-7') || ageRange.includes('6个月')) {
      organized['6-8'].push(recipe);
    } else if (ageRange.includes('8-9') || ageRange.includes('7-8')) {
      organized['8-12'].push(recipe);
    } else if (ageRange.includes('11-12') || ageRange.includes('12个月')) {
      organized['12+'].push(recipe);
    }
  });

  return organized;
}

Page({
  data: {
    primaryColor: '#6366f1',
    crossAgeRecommend: false,
    currentAge: '6-8',
    currentCategory: '主食',
    ingredients: [],
    selectedRecipes: [],
    showRecipeDetail: false,
    currentRecipe: null,
    // 食材分类规则
    categoryRules: {
      '主食': ['米', '面', '馒头', '饼', '粥', '土豆', '南瓜'],
      '肉类': ['肉', '鱼', '虾', '蛋'],
      '蔬菜': ['菜', '瓜', '萝卜', '豆'],
      '水果': ['果', '瓣', '梨', '桃', '柑', '橙']
    },
    foodData: {
      '主食': [
        { name: '米粉', selected: false },
        { name: '面条', selected: false },
        { name: '大米', selected: false },
        { name: '小米', selected: false },
        { name: '意大利面', selected: false },
        { name: '土豆', selected: false },
        { name: '南瓜', selected: false },
        { name: '山药', selected: false },
        { name: '芋头', selected: false }
      ],
      '肉类': [
        { name: '鸡肉', selected: false },
        { name: '牛肉', selected: false },
        { name: '猪肉', selected: false },
        { name: '三文鱼', selected: false },
        { name: '鸡肝', selected: false },
        { name: '虾仁', selected: false },
        { name: '鳕鱼', selected: false }
      ],
      '蔬菜': [
        { name: '胡萝卜', selected: false },
        { name: '西兰花', selected: false },
        { name: '豆腐', selected: false },
        { name: '青菜', selected: false },
        { name: '白菜', selected: false },
        { name: '番茄', selected: false },
        { name: '洋葱', selected: false },
        { name: '香菇', selected: false }
      ],
      '水果': [
        { name: '苹果', selected: false },
        { name: '香蕉', selected: false },
        { name: '牛油果', selected: false }
      ]
    },
    recipeDatabase: organizeRecipesByAge(recipesData),
    isSearching: false,
    aiSuggestions: [],
    selectedAiRecipe: null,
    aiRecipeNames: [],
    aiRecipesData: []
  },

  onLoad() {
    this.setData({
      ingredients: this.data.foodData[this.data.currentCategory]
    })
  },

  // 切换跨月龄推荐
  toggleCrossAge(e) {
    this.setData({
      crossAgeRecommend: e.detail.value
    })
    this.updateRecipes()
  },

  // 更新食谱推荐（支持跨月龄）
  updateRecipes() {
    const selectedIngredients = []
    Object.values(this.data.foodData).forEach(category => {
      category.forEach(item => {
        if (item.selected) {
          selectedIngredients.push(item.name)
        }
      })
    })

    if (selectedIngredients.length === 0) {
      this.setData({ selectedRecipes: [] })
      return
    }

    let recipes = []
    if (this.data.crossAgeRecommend) {
      // 获取所有月龄段的食谱
      Object.entries(this.data.recipeDatabase).forEach(([age, ageRecipes]) => {
        recipes = recipes.concat(ageRecipes.map(recipe => ({
          ...recipe,
          ageRange: age === '6-8' ? '6-8个月' : 
                    age === '8-12' ? '8-12个月' : 
                    '12个月以上'
        })))
      })
    } else {
      // 只获取当前月龄段的食谱
      recipes = this.data.recipeDatabase[this.data.currentAge].map(recipe => ({
        ...recipe,
        ageRange: this.data.currentAge === '6-8' ? '6-8个月' : 
                 this.data.currentAge === '8-12' ? '8-12个月' : 
                 '12个月以上'
      }))
    }

    // 计算匹配度并排序
    const matchedRecipes = recipes.map(recipe => {
      const matchCount = recipe.ingredients.filter(ingredient => 
        selectedIngredients.includes(ingredient)
      ).length
      
      return {
        ...recipe,
        matchRate: Math.round(matchCount / recipe.ingredients.length * 100)
      }
    }).filter(recipe => recipe.matchRate > 0)
    .sort((a, b) => b.matchRate - a.matchRate)

    this.setData({ selectedRecipes: matchedRecipes })
  },

  // 切换月龄
  switchAge(e) {
    const age = e.currentTarget.dataset.age
    this.setData({ currentAge: age })
    this.updateRecipes()
  },

  // 切换食材分类
  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      currentCategory: category,
      ingredients: this.data.foodData[category]
    })
    this.updateRecipes()
  },

  // 选择食材
  selectIngredient(e) {
    const index = e.currentTarget.dataset.index
    const ingredients = this.data.ingredients
    const foodData = this.data.foodData
    
    // 更新选中状态
    ingredients[index].selected = !ingredients[index].selected
    foodData[this.data.currentCategory] = ingredients

    this.setData({ 
      ingredients,
      foodData
    })
    
    this.updateRecipes()
  },

  // 重置选择
  resetSelection() {
    const foodData = this.data.foodData
    // 重置所有食材的选中状态
    Object.keys(foodData).forEach(category => {
      foodData[category].forEach(item => {
        item.selected = false
      })
    })

    this.setData({
      foodData,
      ingredients: foodData[this.data.currentCategory],
      selectedRecipes: []
    })
  },

  // 显示食谱详情
  showRecipeDetail(e) {
    const recipe = e.currentTarget.dataset.recipe
    console.log('点击的食谱:', recipe) // 添加日志
    if (recipe) {
      this.setData({
        showRecipeDetail: true,
        currentRecipe: recipe
      }, () => {
        console.log('弹窗状态:', this.data.showRecipeDetail) // 添加日志
        console.log('当前食谱:', this.data.currentRecipe) // 添加日志
      })
    }
  },

  // 隐藏食谱详情
  hideRecipeDetail() {
    console.log('关闭弹窗') // 添加日志
    this.setData({
      showRecipeDetail: false,
      currentRecipe: null
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
    return false
  }
})
